<?php

declare(strict_types=1);

namespace App\Services\Gift;


use App\Dao\BackpackDao;
use App\Dao\ClosenessDao;
use App\Dao\CommonSettingDao;
use App\Dao\GiftDao;
use App\Dao\SettingDao;
use App\Dao\UserDao;
use App\Event\ChatRoomSendGiftNotify;
use App\Exception\MessageException;
use App\Model\Gift;
use App\Model\GiftAnchor;
use App\Model\Guild;
use App\Model\IncomeExpense;
use App\Model\SendGiftItem;
use App\Model\User;
use App\Model\UserSetting;
use App\Services\PushMessageService;
use App\Services\User\UserWelfareService;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use App\Utils\MemcacheClient;
use App\Utils\MongoDBClient;
use App\Utils\RedisClient;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Throwable;
use function Hyperf\Translation\trans;

class GiftService
{
    #[Inject]
    protected EventDispatcherInterface $eventDispatcher;

    /**
     * Note - 获取礼物列表
     * DateTime 2024/8/16 18:43
     * User Admin
     * @param $userInfo
     * @param $params
     * @return array
     */
    public function list($userInfo, $params)
    {
        $uid = $userInfo['uid'];
        $userId = $params['user_id'] ?? 0;

        //返回礼物列表信息
        // $giftModel = new GiftDao();
        $gift_list = GiftDao::getInstance()->getAllGift(); //取上架的所有礼物，有5分钟缓存

        if ($userInfo['sex'] == 2) {
            // 公会女用户列表礼物价格修改
            // $guild = (new \GuildModel())->find("*", "guild_num=? and status=1", [$userInfo['guild_num']]);
            $guild = Guild::query()->where('guild_num', $userInfo['guild_num'])->where('status', 1)->first();

            if (!empty($guild)) {
                $guild_rate = $guild['anchor_gift_rate'];
                if ($userInfo['send_gift_rate'] > 0) {
                    $guild_rate = $userInfo['send_gift_rate'];
                }
                // 可免费送礼数量
                $freeCount = CommonSettingDao::getValue('free_gift_count', 1);

                // 判断女用户是否送过免费礼物
                $freeGift = SendGiftItem::query()
                    ->selectRaw('gid,count(*) gift_count')
                    ->where('send_uid', $uid)
                    ->where('cost', 0)
                    ->where('get_uid', $userId)
                    ->where('send_time', '>', strtotime(date("Ymd")))
                    ->groupBy('gid')->pluck('gift_count', 'gid')->toArray();

                foreach ($gift_list as &$gift) {
                    $gift['discount_price'] = bcmul(strval($gift['price']), strval($guild_rate / 100), 2);
                    if ($gift['discount_price'] < 1 && $gift['discount_price'] != 0) {
                        $gift['discount_price'] = '1';
                    }
                    $gift['discount_price'] = intval($gift['discount_price']) . "";
                    $gift['is_send'] = '0';
                    if (isset($freeGift[$gift['id']]) && $freeGift[$gift['id']] >= $freeCount) {
                        $gift['is_send'] = '1';
                    }
                }
            }
        }

        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'weixin' => $weixin, 'msg' => array_values($gift_list)), '');
        return formatData(['result' => 1, 'msg' => array_values($gift_list)]);

    }


    /**
     * Note - 发送礼物
     * DateTime 2024/8/16 18:43
     * User Admin
     * @param $userInfo
     * @param $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function sendGift($userInfo, $params)
    {
        $uid = $userInfo['id']; //送礼人，用户
        $session_id = $params['session_id'];
        $user_id = $params['user_id']; //收礼人，主播
        $gid = $params['gid']; //礼物id
        $num = $params['num']; //送礼数量
        $call_id = $params['call_id'] ?? 0; //如果非通话中送礼，则为0
        $is_backpack = $params['is_backpack']; //是否为背包送礼
        $from = $params['from']; //1 安卓 2 IOS
        $version_code = $params['version_code'];
        $package = $params['package'];
        $roomNumber = $params['room_number'] ?? null;// 房间编号

        // 获取礼物信息
        $giftInfo = GiftDao::getInstance()->getGiftCache($gid);
        if (empty($giftInfo) || $giftInfo['status'] == 1) {
            // Tool::JSON(\CodeData::NEED_TIPS, '', '该礼物不存在');
            throw new MessageException('该礼物不存在');
        }
        // 获取收礼人信息
        $toUserInfo = UserDao::getInstance()->findUserInfoCache($user_id);

        $getInfo['sex'] = $toUserInfo['sex'];
        $getInfo['uid'] = $user_id;
        $getInfo['guild_num'] = $toUserInfo['guild_num'];
        $can_send = '0';

        if ($userInfo['sex'] == 2) {
            $guild = Guild::query()->where('guild_num', $userInfo['guild_num'])->where('status', 1)->first();
            if (!empty($guild)) {
                $guild_rate = $guild['anchor_gift_rate'];
                if ($userInfo['send_gift_rate'] > 0) {
                    $guild_rate = $userInfo['send_gift_rate'];
                }
                $giftInfo['origin_price'] = $giftInfo['price'];
                $giftInfo['price'] = bcmul(strval($giftInfo['price']), strval($guild_rate / 100), 2);
                if ($giftInfo['price'] < 1 && $giftInfo['price'] != 0) {
                    $giftInfo['price'] = 1;
                }
                $giftInfo['price'] = intval($giftInfo['price']);
            }

            // 女用户送免费礼物
            if ($giftInfo['price'] == 0) {
                // 可免费送礼数量
                $freeCount = CommonSettingDao::getValue('free_gift_count', 1);
                // 判断女用户是否送过免费礼物
                $times = strtotime(date("Ymd"));
                // $freeGiftCount = $giftModel->findOneField("select count(*) gift_count from tb_send_gift_item where send_uid={$uid} and gid={$gid} and cost=0 and get_uid={$user_id} and send_time>{$times}", "gift_count") ?: 0;
                $sendFreeGiftCount = SendGiftItem::query()->where('send_uid', $uid)
                    ->where('gid', $gid)
                    ->where('cost', 0)
                    ->where('get_uid', $user_id)
                    ->where('send_time', '>', $times)
                    ->count();

                if ($sendFreeGiftCount >= $freeCount) {
                    // Tool::JSON(\CodeData::NEED_TIPS, '', '当前无免费礼物次数');
                    throw new MessageException('当前无免费礼物次数');
                }
                if ($sendFreeGiftCount + 1 < $freeCount) {
                    $can_send = '1';
                }
            }
        }

        $rate = GIFT_DIVIDE_RATE;
        $getInfo['rate'] = $rate;
        $cost = $giftInfo['price'] * $num;


        $closeness = ClosenessDao::read($user_id, $uid);
        $is_limit = FunUtil::chatLimit($uid, $user_id, $closeness);
        if ($userInfo['sex'] == 2 && $is_limit) {
            throw new MessageException('对方账号有异常.');
        }

        if ($userInfo["sex"] == 1) {
            // 用户余额
            $user_info = User::query()->where('id', $uid)->first(['id', 'gift_count', 'sys_send_count', 'recharge_send_count']);
            $user_info = modelToArray($user_info);
            $checkGoldInfo = checkUserGoldCount($user_info, $cost, 1);
            if (!$checkGoldInfo) {
                $desc = '余额不足，无法送礼';
                $call_id > 0 && $desc = '呀~余额不足了呢~';
                // Tool::JSON(\CodeData::SUCCESS, array('result' => 3), $desc);
                throw new MessageException($desc);
            }
        }

        // 发送礼物
        $rs = $this->sendGiftToAnchor($uid, $getInfo, $giftInfo, $num, $call_id, $is_backpack, $userInfo['channel'], $is_limit, $from, $version_code, $package, $roomNumber);


        if ($rs['code'] == 1) {
            $mongo = MongoDBClient::getInstance();
            if ($is_limit && $rs['gold'] > 0) {
                // 记录风险用户扣费 8小时后退回
                $insert = [
                    'uid' => $uid,
                    'to_uid' => strval($user_id),
                    'type' => 2,    // 1-消息 2-礼物
                    'gold' => strval($rs['gold']),
                    'gold_from' => $rs['gold_from'] ?? '',
                    'expend_id' => $rs['expend_id'],
                    'ctime' => time(),
                    'is_return' => 0,
                    'return_time' => 0,
                ];
                $mongo->insert('tb_limit_user_message', $insert);

                // $call_gold = $giftModel->findOneField("select gift_count+sys_send_count+recharge_send_count call_gold from tb_user where id = {$uid}", 'call_gold') ?: '0';
                // 用户送礼之前余额
                $call_gold = User::query()->where('id', $uid)->sum(Db::raw('gift_count+sys_send_count+recharge_send_count'));
                // 亲密度
                $closeness += $rs['gold'];
                // 用户余额
                $gift_count = bcsub(strval($userInfo['gift_count']), strval($rs['gold']));
                // 用户送礼支出
                $gift_amount = 0;
                // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => compact("uid", "gift_count", "gift_amount", 'closeness', 'can_send', 'call_gold')), '送礼成功');
                return formatData([
                    'result' => 1,
                    'msg' => [
                        'uid' => $uid,
                        'gift_count' => $gift_count,
                        'gift_amount' => $gift_amount,
                        'closeness' => $closeness,
                        'can_send' => $can_send,
                        'call_gold' => $call_gold,
                    ]
                ]);
            }


            //送礼成功
            $insertData = array();
            $insertData['uid'] = (int)$uid;
            $insertData['receive_uid'] = (int)$user_id;
            // $insertData['content'] = $userInfo['nickname'] . trans('message.给你送了') . $num . trans('message.个') . '【' . $giftInfo['name'] . '】';
            $insertData['content'] = trans('message.给你送了', ['num' => $num, 'nickname' => $userInfo['nickname'], 'gift' => $giftInfo['name']]);
            $insertData['ctime'] = time();
            $insertData['chat_type'] = 11;  //通话过程中用户送礼
            $insertData['content_type'] = 6; //送礼动画，仅在chat_type=11才有
            $insertData['from'] = $from;
            $insertData['version_code'] = $userInfo['version_code'];
            $insertData['channel_number'] = $userInfo['channel'];
            if ($call_id > 0) {
                //算出主播收礼收入
                $gift_amount = (new Gift())->getGiftProfit($user_id, $call_id);
            } else {
                $gift_amount = 0;
            }
            $gift_data = array(
                'call_id' => $call_id,
                'gid' => $gid,
                'name' => $giftInfo['name'],
                'hk_name' => $giftInfo['hk_name'],
                'en_name' => $giftInfo['en_name'],
                'unit_profit' => (float)bcmul(strval($giftInfo['price']), (string)$rate, 2),
                'img' => FunUtil::formatPhoto($giftInfo['img']),
                'num' => $num,
                'effect_url' => $giftInfo['effect_url'],
                'gift_amount' => $gift_amount,
            );
            $insertData['gift_data'] = json_encode($gift_data);
            $insertData['look'] = 0;  //是否已读
            $insertData['date'] = date("Y-m-d");
            // 是否是新人
            // $insertData['is_new_user'] = (new UserModel())->checkNewUser($uid);
            $insertData['is_new_user'] = UserDao::getInstance()->checkNewUser($uid);
            // $mongo->selectCollection(MON_USER_CHAT);
            $mongo->insert('tb_user_chat_v2', $insertData);

            // $setting = new SettingModel();
            // 送礼信息 0不显示 1显示
            $send_gift_show = intval(SettingDao::getInstance()->getOne('send_gift_show'));
            // 送礼总金币
            $send_gift_count = SettingDao::getInstance()->getOne('send_gift_count');
            // 男用户一次性送礼金币大于【$cost】，发送全服务通知
            $cost = $giftInfo['price'] * $num;
            if ($send_gift_show == 1 && $send_gift_count <= $cost && $userInfo['sex'] == 1) {
                if ($cost < 999) {
                    $wait = 3;
                } elseif ($cost < 2999) {
                    $wait = 10;
                } elseif ($cost < 5000) {
                    $wait = 20;
                } else {
                    $wait = 30;
                }
                // $settingModel = new UserSettingModel();
                // $hide = $settingModel->findAll("uid,hidden_nick", "uid in ($uid,$user_id)", [1]);
                $hidden = UserSetting::query()->whereIn('uid', [$uid, $user_id])->pluck('hidden_nick', 'uid')->toArray();
                // $hidden = [];
                // if (!empty($hide)) {
                //     $hidden = array_column($hide, "hidden_nick", 'uid');
                // }


                $data = [
                    'uid' => $userInfo['id'],
                    'notice_type' => 2,           // 2飘窗消息
                    'nickname' => (!isset($hidden[$uid]) || $hidden[$uid] == 1) ? trans('message.神秘人') : $userInfo['nickname'],
                    'head_image' => (!isset($hidden[$uid]) || $hidden[$uid] == 1) ? 'https://magoo.oss-ap-southeast-1.aliyuncs.com/default/default/headimg/mysterious.png' : $userInfo['head_image'],
                    'sex' => (int)$userInfo['sex'],
                    'user_nickname' => (!isset($hidden[$user_id]) || $hidden[$user_id] == 1) ? trans('message.神秘人') : $toUserInfo['nickname'],
                    'user_head_image' => (!isset($hidden[$user_id]) || $hidden[$user_id] == 1) ? 'https://magoo.oss-ap-southeast-1.aliyuncs.com/default/default/headimg/mysterious.png' : $toUserInfo['head_image'],
                    'user_sex' => (int)$toUserInfo['sex'],
                    'user_id' => $user_id,
                    'img' => $giftInfo['img'],
                    'name' => $giftInfo['name'],
                    'hk_name' => $giftInfo['hk_name'],
                    'en_name' => $giftInfo['en_name'],
                    'num' => $num,
                    'wait' => $wait,
                    'sub_type' => 1,
                ];
                FunUtil::socket_client('notice', $uid, $session_id, $data);
            }
            // Fun::socket_client('send', $uid, $session_id, array($user_id));
            // (new WyyClient())->send_gift(array($user_id));
            PushMessageService::putYunXinSendGiftQueue($user_id);


            // 判断是否升级，发送升级im消息
            if ($userInfo['sex'] == 2) {
                $closeness = ClosenessDao::read($user_id, $uid);
                ClosenessDao::sendClosenessUpgradeMsg($user_id, $uid, $rs['cost'], $closeness - $rs['cost']);
            } else {
                $closeness = ClosenessDao::read($uid, $user_id);
                ClosenessDao::sendClosenessUpgradeMsg($uid, $user_id, $rs['cost'], $closeness - $rs['cost']);
            }

            // $gift_count = $rs['gift_count'];
            $gift_count = bcsub(strval($rs['gift_count']), strval($rs['cost']));
            if ($call_id > 0) {
                //算出用户送礼支出
                $gift_amount = GiftDao::getInstance()->getGiftCost($uid, $call_id);
            } else {
                $gift_amount = 0;
            }

            // $call_gold = $giftModel->findOneField("select gift_count+sys_send_count+recharge_send_count call_gold from tb_user where id = {$uid}", 'call_gold') ?: '0';
            $call_gold = User::query()->where('id', $uid)->sum(Db::raw('gift_count+sys_send_count+recharge_send_count'));

            // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => compact("uid", "gift_count", "gift_amount", 'closeness', 'can_send', 'call_gold')), '送礼成功');
            return formatData([
                'result' => 1,
                'msg' => [
                    'uid' => $uid,
                    'gift_count' => $gift_count,
                    'gift_amount' => $gift_amount,
                    'closeness' => $closeness,
                    'can_send' => $can_send,
                    'call_gold' => $call_gold,
                ]
            ]);

        } elseif ($rs['code'] == -1) {
            // $desc = '余额不足，无法送礼';
            // $call_id > 0 && $desc = '呀~余额不足了呢~';
            // Tool::JSON(\CodeData::SUCCESS, array('result' => 3), $desc);
            throw new MessageException($rs['msg']);
        } else {
            LoggerUtil::write('gift_send_fail', $rs['msg']);
            // Tool::JSON(\CodeData::NEED_TIPS, '', '送礼失败');
            throw new MessageException('送礼失败');
        }

    }


    /**
     * Note - 用户送礼给主播
     * DateTime 2024/8/19 16:19
     * User Admin
     * @param $send_uid -送礼方，用户
     * @param $getInfo -收礼方信息
     * @param $giftInfo -礼物属性
     * @param $num -礼物数量
     * @param $call_id -通话id，如果为0表示不是在通话中送礼
     * @param $is_backpack -是否为背包送礼
     * @param $channel -来源
     * @param $is_limit -是否限制送礼
     * @param $from -系统类型
     * @param $version_code -版本号
     * @param $package -包名
     * @return array
     */
    public function sendGiftToAnchor($send_uid, $getInfo, $giftInfo, $num, $call_id = 0, $is_backpack = 0, $channel = '', $is_limit = 0, $from = 1, $version_code = '', $package = '', $roomNumber = '')
    {
        try {
            Db::beginTransaction();
            $get_uid = $getInfo['uid'];
            $cost = $giftInfo['price'] * $num;
            $profit = 0;

            // 用户余额
            // $user = $this->userModel->find('id,gift_count,sys_send_count,recharge_send_count', 'id = ?', array($send_uid));
            $user = User::query()->where('id', $send_uid)->first(['id', 'gift_count', 'sys_send_count', 'recharge_send_count']);
            $user = modelToArray($user);

            $gift_count = 0;    // 普通金币
            $sys_send_count = 0;    // 系统赠送金币
            $recharge_send_count = 0;    // 充值赠送金币
            $checkGold = [];
            $rate_arr = [];

            if ($cost > 0) {
                if ($is_backpack == 0) {
                    $checkGold = checkUserGoldCount($user, $cost, 1);
                    if ($checkGold) {
                        // extract($checkGold);
                        $gift_count = $checkGold['gift_count'];    // 普通金币
                        $sys_send_count = $checkGold['sys_send_count'];    // 系统赠送金币
                        $recharge_send_count = $checkGold['recharge_send_count'];    // 充值赠送金币
                    } else {
                        throw new \Exception("余额不足，无法送礼", -1);
                    }


                    // 扣除系统增送金币
                    if ($sys_send_count > 0) {
                        $sys_rate = CommonSettingDao::getValue('system_send_gold_rate');
                        $rate_arr['system_send_rate'] = $sys_rate;
                        $profit = bcmul((string)$sys_send_count, (string)$sys_rate, 2);

                        // $this->userModel->updateByWhereSet("sys_send_count=sys_send_count-{$sys_send_count}","id={$send_uid}");
                        User::query()->where('id', $send_uid)->decrement('sys_send_count', $sys_send_count);
                    }

                    // 扣除充值赠送金币
                    if ($recharge_send_count > 0) {
                        $rec_rate = CommonSettingDao::getValue('recharge_send_gold_rate');
                        $rate_arr['recharge_send_rate'] = $rec_rate;
                        $profit = bcadd((string)$profit, strval($recharge_send_count * $rec_rate), 2);

                        // $this->userModel->updateByWhereSet("recharge_send_count=recharge_send_count-{$recharge_send_count}","id={$send_uid}");
                        User::query()->where('id', $send_uid)->decrement('recharge_send_count', $recharge_send_count);
                    }

                    // 扣除普通金币
                    if ($gift_count > 0) {
                        $profit = bcadd((string)$profit, strval($gift_count * $getInfo['rate']), 2);
                        $rs1 = UserDao::getInstance()->reduceUserAccount($send_uid, $gift_count);
                    }
                } else {
                    // $model = new BackPackModel();
                    $rs1 = BackpackDao::getInstance()->reduceUserGiftNum($send_uid, $giftInfo['id'], $num);
                    if (!$rs1) {
                        throw new \Exception("背包礼物数量不足，无法送礼", -1);
                    }
                }

                if (!$is_limit) {
                    $rs2 = UserDao::getInstance()->addAnchorAccount($get_uid, $profit);
                    if (!$rs2) {
                        throw new \Exception("增加积分失败", -2);
                    }
                } else {
                    $profit = 0;
                }

            }


            $time = time();
            $send_gift_item = array();
            $send_gift_item['send_uid'] = $send_uid;
            $send_gift_item['get_uid'] = $get_uid;
            $send_gift_item['call_id'] = $call_id;
            $send_gift_item['gid'] = $giftInfo['id'];
            $send_gift_item['num'] = $num;
            $send_gift_item['cost'] = $cost;
            $send_gift_item['profit'] = $profit;
            $send_gift_item['send_time'] = $time;
            $send_gift_item['from'] = $from;
            $send_gift_item['version_code'] = $version_code;
            $send_gift_item['channel'] = $channel;
            if (!empty($roomNumber)) {
                $chat_room_send_gift_item = $send_gift_item;
                $chat_room_send_gift_item['room_number'] = $roomNumber;
                unset($chat_room_send_gift_item['call_id']);
                $this->eventDispatcher->dispatch(new ChatRoomSendGiftNotify($chat_room_send_gift_item));
            }
            // $giftModel = new GiftModel();
            // $rs3 = $giftModel->insert($send_gift_item, 'tb_send_gift_item');
            $rs3 = SendGiftItem::query()->insert($send_gift_item);
            if (!$rs3) {
                throw new \Exception("生成送礼记录失败", -3);
            }

            // 免费送礼给男用户
            if ($cost == 0 && $getInfo['sex'] == 1) {
                // 记录用户亲密度
                if ($giftInfo['origin_price'] < 100) {
                    // 礼物价格
                    $cost = $giftInfo['origin_price'];
                } elseif ($giftInfo['origin_price'] < 1000) {
                    $cost = rand(100, 200);
                } else {
                    $cost = rand(200, 500);
                }
                ClosenessDao::write($get_uid, $send_uid, $cost, false);

                Db::commit();
                return array('code' => 1, 'msg' => '成功', 'gift_count' => $user['gift_count'], 'cost' => $cost);
            }

            // 统计该主播收到该礼物的数量
            // $gift_num = $giftModel->getList($get_uid, $giftInfo['id']);
            $gift_num = GiftAnchor::query()->where('anchor_id', $get_uid)->where('gift_id', $giftInfo['id'])->first();
            $arr['anchor_id'] = $get_uid;
            $arr['gift_id'] = $giftInfo['id'];
            if ($gift_num) {
                $arr['num'] = (int)$gift_num['num'] + (int)$num;
                $arr['time'] = $time;
                GiftAnchor::query()->where('id', $gift_num['id'])->update($arr);
            } else {
                $arr['num'] = (int)$num;
                $arr['time'] = $time;
                GiftAnchor::query()->insert($arr);
            }


            // $rs5 = $this->userModel->find('id,inviteUid,gift_count,integrate_usable_count,integrate_freeze_count,`from`,version_code,channel,register_ip,sex,is_robot,package', 'id = ?', array($get_uid));
            // 收礼人资金数据
            $getGiftUserInfo = User::query()
                ->select(['id', 'inviteUid', 'gift_count', 'integrate_usable_count', 'integrate_freeze_count', 'from', 'version_code', 'channel', 'register_ip', 'sex', 'is_robot', 'package'])
                ->where('id', $get_uid)->first();
            if (!$getGiftUserInfo) {
                throw new \Exception("查询用户信息失败", -5);
            }
            $getGiftUserInfo = $getGiftUserInfo->toArray();

            // 插入用户支出流水
            $user_expense = array();
            $user_expense['uid'] = $send_uid;
            $user_expense['type'] = 2;//支出
            $user_expense['sub_type'] = 12;//送礼支出
            $user_expense['amount_type'] = 1;//金币
            $user_expense['amount'] = $cost;
            $user_expense['account'] = $user['gift_count'] - $gift_count;
            $user_expense['user_id'] = $get_uid;
            $anchor_income['ext'] = json_encode(['p' => $getGiftUserInfo['package'], 'v' => $getGiftUserInfo['version_code'], 'c' => $getGiftUserInfo['channel']]);
            $user_expense['ctime'] = $time;
            $user_expense['extend'] = json_encode(['gift_id' => $giftInfo['id'], 'gift_num' => $num, 'gift_name' => $giftInfo['name'], 'call_id' => $call_id]);
            $user_expense['from'] = $from;
            $user_expense['ip'] = FunUtil::getClientIp();
            $user_expense['version_code'] = $version_code;
            $user_expense['package'] = $package;
            $user_expense['channel'] = $channel;
            $user_expense['guild_num'] = '';
            $user_expense['gold_from'] = json_encode($checkGold);
            // $rs4 = $this->payCallModel->insert($user_expense, 'tb_income_expense');
            $rs4 = IncomeExpense::query()->insertGetId($user_expense);
            if (!$rs4) {
                throw new \Exception("生成用户支出流水失败", -4);
            }


            // 记录用户亲密度
            if ($getInfo['sex'] == 2) {
                if (!$is_limit) {
                    ClosenessDao::write($send_uid, $get_uid, $cost, false);
                    // 增加男用户财富值，女用户魅力值
                    UserDao::getInstance()->addUserWealth($send_uid, $get_uid, $cost);
                } else {
                    // 记录临时亲密度
                    $redis = RedisClient::getInstance();
                    $tmp = $redis->hGet("tmp_closeness:$send_uid", $get_uid) ?: 0;
                    $redis->hSet("tmp_closeness:$send_uid", $get_uid, $tmp + $cost);
                    // 风险用户送礼不计用户收入
                    Db::commit();
                    return array('code' => 1, 'msg' => '成功', 'gold' => $cost, 'gold_from' => json_encode($checkGold), 'expend_id' => $rs4);
                }
            } else {
                ClosenessDao::write($get_uid, $send_uid, $cost, false);
            }


            $anchor_income = array();
            $anchor_income['uid'] = $get_uid;
            $anchor_income['type'] = 1;//收入
            $anchor_income['sub_type'] = 3;//收礼收入
            $anchor_income['amount_type'] = 2;//积分
            $anchor_income['amount'] = $profit;
            $anchor_income['account'] = $getGiftUserInfo['integrate_usable_count'] + $getGiftUserInfo['integrate_freeze_count'];
            $anchor_income['user_id'] = $send_uid;
            $anchor_income['ext'] = json_encode(['p' => $package, 'v' => $version_code, 'c' => $channel]);
            $anchor_income['ctime'] = $time;
            $anchor_income['rate'] = $getInfo['rate'] * 100;
            $anchor_income['extend'] = json_encode(['gift_id' => $giftInfo['id'], 'gift_num' => $num, 'gift_name' => $giftInfo['name'], 'call_id' => $call_id]);
            $anchor_income['from'] = $getGiftUserInfo['from'];
            $anchor_income['ip'] = $getGiftUserInfo['register_ip'];
            $anchor_income['version_code'] = (int)$getGiftUserInfo['version_code'];
            $anchor_income['package'] = $getGiftUserInfo['package'];
            $anchor_income['channel'] = $getGiftUserInfo['channel'];
            $anchor_income['guild_num'] = $getInfo['guild_num'];
            $anchor_income['gold_from'] = json_encode(array_merge($checkGold, $rate_arr));
            $rs6 = IncomeExpense::query()->insert($anchor_income);
            if (!$rs6) {
                throw new \Exception("生成用户收入流水失败", -6);
            }
            Db::commit();
            //邀请人收益
            if (!empty($rs5['inviteUid'])) {
                (new UserWelfareService())->welfare_InvitedUsers($get_uid, $rs6, $rs5['inviteUid'], 4);
            }
            MemcacheClient::getInstance()->delete("userInfo_" . $send_uid);
            MemcacheClient::getInstance()->delete("userInfo_" . $get_uid);
            return array('code' => 1, 'msg' => '成功', 'gift_count' => $user['gift_count'], 'cost' => $cost);
        } catch (Throwable $e) {
            Db::rollBack();
            return array('code' => $e->getCode(), 'msg' => $e->getMessage());
        }
    }


}